package com.wingsfrog.tabs.app;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.wingsfrog.ui.Carousel;
import com.wingsfrog.ui.GridViewInScrollView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by johnson on 15/12/29.
 */
public class MainTab01 extends Fragment {
    private static String url = "http://test.yueguanjia.com/jielin-web/customer/product?city=310100&token=6aed23c6b2c7f01312c205cd97ba0495";
    private Carousel carousel;
    private GridViewInScrollView gridviewInSv_2col;
    private GridViewInScrollView gridviewInSv_3col;
    private Integer[] imgIds3 = {
            R.drawable.banner6, R.drawable.banner7,
            R.drawable.banner6, R.drawable.banner7,
            R.drawable.banner6
    };
    private Integer[] imgIds2 = {
            R.drawable.banner6, R.drawable.banner7
    };
    RequestQueue mQueue;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mQueue = Volley.newRequestQueue(getActivity());
        View view = inflater.inflate(R.layout.main_tab_01, container, false);
        carousel = (Carousel) view.findViewById(R.id.carousel_topView);
        gridviewInSv_2col = (GridViewInScrollView) view.findViewById(R.id.gridviewInSv_2col);
        gridviewInSv_3col = (GridViewInScrollView) view.findViewById(R.id.gridviewInSv_3col);
        StringRequest stringRequest = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("TAG", response);

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jsonArray = jsonObject.getJSONArray("body");
                            int lenght = jsonArray.length();
                            String[] txts2 = new String[2];
                            String[] urls2 = new String[2];
                            String[] txts3 = new String[lenght-2];
                            String[] urls3 = new String[lenght-2];
                            for (int i=0;i<lenght;i++) {
                                if (i < 2) {
                                    txts2[i] = jsonArray.getJSONObject(i).getString("name");
                                    urls2[i] = jsonArray.getJSONObject(i).getString("serviceIcon");
                                }else{
                                    txts3[i-2] = jsonArray.getJSONObject(i).getString("name");
                                    urls3[i-2] = jsonArray.getJSONObject(i).getString("serviceIcon");
                                }

                            }
                            gridviewInSv_2col.setAdapter(new gridInScrollAdapter(getActivity(), R.layout.home_service_item, urls2,txts2, 2));
                            gridviewInSv_3col.setAdapter(new gridInScrollAdapter(getActivity(), R.layout.home_service_item, urls3,txts3, 3));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }
        });
        mQueue.add(stringRequest);
        List<Carousel.ImageInfo> list = new ArrayList<Carousel.ImageInfo>();
        list.add(new Carousel.ImageInfo(R.drawable.banner6, "", ""));
        list.add(new Carousel.ImageInfo(R.drawable.banner7, "", ""));
        list.add(new Carousel.ImageInfo(R.drawable.banner8, "", ""));
        carousel.loadData(list, new Carousel.LoadImageCallBack() {
            @Override
            public ImageView loadAndDisplay(Carousel.ImageInfo imageInfo) {
                //本地图片
                ImageView imageView = new ImageView(getActivity());
                imageView.setImageResource(Integer.parseInt(imageInfo.image.toString()));
                return imageView;
            }
        });
        return view;
    }

    public final class ViewHolder {
        public ImageView home_service_item_iv;
        public TextView home_service_item_tv;
    }

    private class gridInScrollAdapter extends BaseAdapter {
        int screenWidth;
        int screenHeight;
        int cols;
        int viewResourceId;
        private Context context;
        private String[] urls;
        private String[] txts;
        private LayoutInflater mInflater;


        public gridInScrollAdapter(Context context, int viewResourceId, String[] urls,String[] txts, int cols) {
            this.context = context;
            this.mInflater = LayoutInflater.from(context);
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            screenWidth = wm.getDefaultDisplay().getWidth();
            screenHeight = wm.getDefaultDisplay().getHeight();
            this.urls = urls;
            this.cols = cols;
            this.viewResourceId = viewResourceId;
            this.txts = txts;
        }

        @Override
        public int getCount() {
            return urls.length;
        }

        @Override
        public Object getItem(int position) {
            return urls[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int boxWidth = screenWidth / cols;
            ViewHolder holder = null;
            ImageView imageView;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(viewResourceId, null);
                convertView.setLayoutParams(new GridView.LayoutParams(boxWidth, boxWidth));
                holder.home_service_item_iv = (ImageView) convertView.findViewById(R.id.home_service_item_iv);
                holder.home_service_item_tv = (TextView) convertView.findViewById(R.id.home_service_item_tv);
                convertView.setTag(holder);
//                imageView.setPadding(8, 8, 8, 8);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
            if (urls != null) {
                ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
                ImageListener listener = ImageLoader.getImageListener(holder.home_service_item_iv, R.drawable.banner6, R.drawable.banner7);
                imageLoader.get(urls[position], listener);
            }
            if (txts != null) {
                holder.home_service_item_tv.setText(txts[position]);
            }

            return convertView;
        }
    }
    public class BitmapCache implements ImageCache {

        private LruCache<String, Bitmap> cache;

        public BitmapCache() {
            cache = new LruCache<String, Bitmap>(8 * 1024 * 1024) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            };
        }

        @Override
        public Bitmap getBitmap(String url) {
            return cache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            cache.put(url, bitmap);
        }
    }


}
